package com.example.myapplication;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
import androidx.activity.result.ActivityResult;
import androidx.activity.result.ActivityResultCallback;
import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.core.content.FileProvider;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

public class AI1 extends AppCompatActivity {
    // 文件提供者的授权信息
    private static final String FILE_PROVIDER_AUTHORITY = "com.example.myapplication.fileprovider";
    // 当前拍照图片的路径
    private String currentPhotoPath;
    // 拍照的 ActivityResultLauncher
    private ActivityResultLauncher<Intent> takePictureLauncher;
    // 从相册选择图片的 ActivityResultLauncher
    private ActivityResultLauncher<Intent> pickPhotoLauncher;
    private static final int PERMISSION_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ai1);
        // 检查并请求权限
        checkAndRequestPermissions();
        // 初始化拍照的 ActivityResultLauncher
        takePictureLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK) {
                            // 提示拍照成功
                            Toast.makeText(AI1.this, "拍照成功", Toast.LENGTH_SHORT).show();
                            // 处理拍照返回的图片
                            File imageFile = new File(currentPhotoPath);
                            analyzeImage(imageFile);
                            showUploadSuccessToast();
                        }
                    }
                });

        // 初始化从相册选择图片的 ActivityResultLauncher
        pickPhotoLauncher = registerForActivityResult(
                new ActivityResultContracts.StartActivityForResult(),
                new ActivityResultCallback<ActivityResult>() {
                    @Override
                    public void onActivityResult(ActivityResult result) {
                        if (result.getResultCode() == RESULT_OK) {
                            // 处理从相册选择的图片
                            Intent data = result.getData();
                            if (data != null) {
                                Uri selectedImageUri = data.getData();
                                if (selectedImageUri != null) {
                                    try {
                                        File imageFile = new File(getRealPathFromURI(selectedImageUri));
                                        analyzeImage(imageFile);
                                        showUploadSuccessToast();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                        Toast.makeText(AI1.this, "处理图片时出现错误", Toast.LENGTH_SHORT).show();
                                    }
                                }
                            }
                        }
                    }
                });

        // 拍照按钮点击事件
        ImageView takePhotoButton = findViewById(R.id.takephoto);
        takePhotoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkPermissions()) {
                    takePicture();
                } else {
                    checkAndRequestPermissions();
                }
            }
        });

        // 反转镜头按钮点击事件
        ImageView reverseCameraButton = findViewById(R.id.Fan);
        reverseCameraButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                reverseCamera();
            }
        });

        // 从相册导入图片按钮点击事件
        ImageView photoAlbumButton = findViewById(R.id.photoalbum);
        photoAlbumButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (checkPermissions()) {
                    pickPhotoFromAlbum();
                } else {
                    checkAndRequestPermissions();
                }
            }
        });
    }

    private void checkAndRequestPermissions() {
        List<String> permissions = new ArrayList<>();
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(android.Manifest.permission.CAMERA);
        }
        if (android.os.Build.VERSION.SDK_INT < android.os.Build.VERSION_CODES.Q &&
                ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(android.Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }
        if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            permissions.add(android.Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        if (!permissions.isEmpty()) {
            ActivityCompat.requestPermissions(this, permissions.toArray(new String[0]), PERMISSION_REQUEST_CODE);
        }
    }

    private boolean checkPermissions() {
        boolean cameraPermission = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
        boolean writePermission = android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.Q ||
                ContextCompat.checkSelfPermission(this, android.Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        boolean readPermission = ContextCompat.checkSelfPermission(this, android.Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
        return cameraPermission && writePermission && readPermission;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == PERMISSION_REQUEST_CODE) {
            boolean allPermissionsGranted = true;
            for (int result : grantResults) {
                if (result != PackageManager.PERMISSION_GRANTED) {
                    allPermissionsGranted = false;
                    break;
                }
            }
            if (!allPermissionsGranted) {
                Toast.makeText(this, "权限被拒绝，部分功能可能无法使用", Toast.LENGTH_SHORT).show();
            }
        }
    }

    /**
     * 启动拍照功能
     */
    private void takePicture() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
            File photoFile = null;
            try {
                photoFile = createImageFile();
            } catch (IOException ex) {
                ex.printStackTrace();
                Toast.makeText(this, "创建图片文件失败", Toast.LENGTH_SHORT).show();
            }
            if (photoFile != null) {
                Uri photoURI = FileProvider.getUriForFile(this,
                        FILE_PROVIDER_AUTHORITY,
                        photoFile);
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, photoURI);
                takePictureLauncher.launch(takePictureIntent);
            }
        }
    }

    /**
     * 反转相机功能（待实现）
     */
    private void reverseCamera() {
        // 这里只是简单提示，实际中需要实现反转相机逻辑
        Toast.makeText(this, "反转镜头功能待实现", Toast.LENGTH_SHORT).show();
    }

    /**
     * 从相册选择图片
     */
    private void pickPhotoFromAlbum() {
        Intent pickPhotoIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickPhotoLauncher.launch(pickPhotoIntent);
    }

    /**
     * 创建图片文件
     * @return 图片文件
     * @throws IOException 创建文件时可能抛出的异常
     */
    private File createImageFile() throws IOException {
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        File storageDir = getExternalFilesDir(null);
        File image = File.createTempFile(
                imageFileName,
                ".jpg",
                storageDir
        );
        currentPhotoPath = image.getAbsolutePath();
        return image;
    }

    /**
     * 根据 Uri 获取图片的真实路径
     * @param contentUri 图片的 Uri
     * @return 图片的真实路径
     */
    private String getRealPathFromURI(Uri contentUri) {
        String[] proj = {MediaStore.Images.Media.DATA};
        android.database.Cursor cursor = getContentResolver().query(contentUri, proj, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            String result = cursor.getString(column_index);
            cursor.close();
            return result;
        }
        return null;
    }

    /**
     * 分析图片
     * @param imageFile 图片文件
     */
    private void analyzeImage(File imageFile) {
        // 在这里进行图片分析，判断患者疾病
        // 可以使用机器学习模型，如 TensorFlow Lite
        // 以下是一个简单的示例，实际应用中需要替换为真实的模型和分析逻辑
        // 示例：假设这里只是打印图片路径
        System.out.println("分析图片: " + imageFile.getAbsolutePath());
    }

    /**
     * 显示图片上传成功的提示
     */
    private void showUploadSuccessToast() {
        Toast.makeText(this, "图片上传成功", Toast.LENGTH_SHORT).show();
    }
}












